﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using TuringVM.Core;

namespace TuringVM.Esoteric.Commands
{
    class LoopEndCommand : CommandBase
    {
        public override byte Code
        {
            get { return 8; }
        }

        public override string Name
        {
            get { return "LoopEnd"; }
        }

        public override byte Execute(Tape code, Tape data)
        {
            if (data.Value != 0)
            {
                int counter = 0;
                do
                {                    
                    code.Position--;
                    if (code.Value == 8) // LoopEnd
                    {
                        counter++;
                    }
                    else if (code.Value == 7) // LoopBegin
                    
                    {
                        if (counter > 0)
                            counter--;
                        else
                            break;
                    }
                } while (true);
            }
            return 0;
        }
    }
}
